package org.apache.doris.demo.spring.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.doris.demo.spring.model.Tag;
import org.apache.doris.demo.spring.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class TagsController {
    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String index(Model model) {
        List<Tag> tags = tagService.list(null);
        model.addAttribute("tags", tags);
        return "/tags/index";
    }

    @GetMapping("/tags/add")
    public String addForm(Model model) {
        model.addAttribute("tag", new Tag());
        return "tags/add";
    }

    @PostMapping("/tags/add")
    public String addTag(@ModelAttribute Tag tag) {
        tag.setTagId(LocalDate.now().toEpochDay() * 24 * 60 * 60 );
        tag.setTimestamp(LocalDateTime.now());
        tag.setDate(LocalDate.now());
        tagService.save(tag);
        return "redirect:/tags";
    }

    @GetMapping("/tags/edit/{name}")
    public String editForm(@PathVariable String name, Model model) {
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("tag_name",name);
        List<Tag> list = tagService.list(tagQueryWrapper);
        if (list.size()>0) {
        Tag tag = list.get(0);
            model.addAttribute("tag", tag);
            return "tags/edit";
        } else {
            return "redirect:/tags";
        }
    }

    @PostMapping("/tags/edit/{name}")
    public String editTag(@PathVariable String name, @ModelAttribute Tag tag) {
        QueryWrapper<Tag> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("distinct_id", tag.getTagType());
        tagService.update(updateWrapper);
        tagService.save(tag);
        return "redirect:/tags";
    }

    @GetMapping("/tags/delete/{name}")
    public String deleteTag(@PathVariable String name) {
        Map<String, Object> tags = new HashMap<>();
        tags.put("tag_name", name);
        tagService.removeByMap(tags);
        return "redirect:/tags";
    }
    @ResponseBody
    @GetMapping("/tags/search/{keyword}")
    public List<Tag> searchTags(@PathVariable ("keyword") String keyword) {
        return tagService.searchTagsByKeyword(keyword);
    }
    @ResponseBody
    @GetMapping("/tags/search/")
    public List<Tag> searchAllTags() {
        return tagService.list();
    }
}